package com.fencing_squad.homo.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fencing_squad.homo.util.function.Reject;
import com.fencing_squad.homo.util.function.Resolve;
import com.zzrv5.mylibrary.ZZRCallBack;
import com.zzrv5.mylibrary.ZZRHttp;

import java.util.HashMap;
import java.util.Map;

public class Network {
    public final static String baseURL = "http://120.77.218.171:5050/api";
//    public final static String baseURL = "http://192.168.31.168:5050/api";
//    public final static String baseURL = "http://192.168.3.184:5050/api";

    public static ZZRCallBack.CallBackString getCallback(Resolve resolve, Reject reject) {
        return new ZZRCallBack.CallBackString() {
            @Override
            public void onFailure(int code, String message) {
                if (reject != null) {
                    reject.func(code, message);
                }
            }

            @Override
            public void onResponse(String response) {
                JSONObject res = JSON.parseObject(response);
                if (res == null) {
                    System.out.println("response " + response);
                    return;
                }
                if(res.getIntValue("code") != 200) {
                    if (reject != null) {
                        reject.func(404, res.getString("msg"));
                    }
                } else {
                    if (resolve != null) {
                        resolve.func(res);
                    }
                }
            }
        };
    }

    public static void postJson(String url, String json, Resolve resolve, Reject reject) {
        Map<String, String> headerMap = new HashMap<>();
        addToken(headerMap);
        ZZRHttp.postJson(baseURL + url, json, headerMap, getCallback(resolve, reject));
    }

    public static void get(String url, Map<String, String> paramsMap, Resolve resolve, Reject reject) {
        Map<String, String> headerMap = new HashMap<>();
        addToken(headerMap);
        ZZRHttp.get(baseURL + url, paramsMap, headerMap, getCallback(resolve, reject));
    }

    public static void get(String url, Resolve resolve, Reject reject) {
        Map<String, String> headerMap = new HashMap<>();
        addToken(headerMap);
        ZZRHttp.get(baseURL + url, null, headerMap, getCallback(resolve, reject));
    }

    public static void addToken(Map<String, String> headerMap) {
        headerMap.put("Authorization", Data.Account.token.equals("") ? null : "Bearer " + Data.Account.token);
    }

    public static String getBaseURL() {
        return baseURL;
    }
}
